package com.titar.robot.utils;

import android.graphics.Bitmap;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import static android.R.attr.key;

/**
 * 描述 TODO
 * 上传头像工具类
 * @author spring sky<br>
 * 支持上传文件和参数
 * Created by john on 2016/1/20.
 */
public class UploadHeadUtil {
	private static UploadHeadUtil uploadUtil;
	private static final String BOUNDARY =  UUID.randomUUID().toString();
	private static final String PREFIX = "--";
	private static final String LINE_END = "\r\n";
	private static final String CONTENT_TYPE = "multipart/form-data";
	private UploadHeadUtil() {

	}

	/**
	 * 描述 TODO
	 * 单例模式获取上传工具类
	 * @return
	 */
	public static UploadHeadUtil getInstance() {
		if (null == uploadUtil) {
			uploadUtil = new UploadHeadUtil();
		}
		return uploadUtil;
	}

	private static final String TAG = "UploadUtil";
	private int readTimeOut = 10 * 1000; // 读取超时
	private int connectTimeout = 10 * 1000; // 超时时间
	/***
	 * 描述 TODO
	 * 请求使用多长时间
	 */
	private static int requestTime = 0;

	private static final String CHARSET = "utf-8"; // 设置编码

	/***
	 * 描述 TODO
	 * 上传成功
	 */
	public static final int UPLOAD_SUCCESS_CODE = 1;
	/**
	 * 描述 TODO
	 * 文件不存在
	 */
	public static final int UPLOAD_FILE_NOT_EXISTS_CODE = 2;
	/**
	 * 描述 TODO
	 * 服务器出错
	 */
	public static final int UPLOAD_SERVER_ERROR_CODE = 3;
	protected static final int WHAT_TO_UPLOAD = 1;
	protected static final int WHAT_UPLOAD_DONE = 2;

	/**
	 * 描述 TODO
	 * android上传文件到服务器
	 * param filePath 需要上传的文件的路径
	 * param fileKey  在网页上<input type=file name=xxx/> xxx就是这里的fileKey
	 * param RequestURL  请求的URL
	 */
	public void uploadFile(Bitmap file, String fileKey, String RequestURL, Map<String, String> param) {
		if (file == null) {
			sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");
			return;
		}
		try {
			uploadFile2(file, fileKey, RequestURL, param);
		} catch (Exception e) {
			sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");
			e.printStackTrace();
			return;
		}
	}

	public void uploadErrorFile(final File file, final String fileKey, final String RequestURL, Map<String, String> param) {
		if (file == null) {
			sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");
			return;
		}
		try {
			Log.i("CrashHandler","param==  "+param.toString());
			uploadErrorFile2(file, fileKey,RequestURL,param);
		} catch (Exception e) {
			Log.i("CrashHandler","fileName==  文件出错");
			sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件出错");
			e.printStackTrace();
			return;
		}
	}

	public void uploadErrorFile2(final File file, final String fileKey, final String RequestURL, final Map<String, String> param) {
		if (file == null ) {
			sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");
			return;
		}
		new Thread(new Runnable() {
			public void run() {
				toUploadErrorFile(file, fileKey, RequestURL,param);
			}
		}).start();

	}

	/**
	 * 描述 TODO
	 * android上传文件到服务器
	 * param file 需要上传的文件
	 * param fileKey  在网页上<input type=file name=xxx/> xxx就是这里的fileKey
	 * param RequestURL  请求的URL
	 */
	public void uploadFile2(final Bitmap file, final String fileKey, final String RequestURL, final Map<String, String> param) {
		if (file == null ) {
			sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");
			return;
		}
		new Thread(new Runnable() {
			public void run() {
				toUploadFile(file, fileKey, RequestURL, param);
			}
		}).start();

	}

	private void toUploadFile(Bitmap file, String fileKey, String RequestURL, Map<String, String> param) {
		String result = null;
		requestTime= 0;

		long requestTime = System.currentTimeMillis();
		long responseTime = 0;

		try {
			URL url = new URL(RequestURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(readTimeOut);
			conn.setConnectTimeout(connectTimeout);
			conn.setDoInput(true); // 允许输入流
			conn.setDoOutput(true); // 允许输出流
			conn.setUseCaches(false); // 不允许使用缓存
			conn.setRequestMethod("POST"); // 请求方式
			conn.setRequestProperty("Charset", CHARSET); // 设置编码
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
			//conn.setRequestProperty("Content-Type", CONTENT_TYPE);
//			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			/**
			 * 描述 TODO
			 * 当文件不为空，把文件包装并且上传
			 */
			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
			StringBuffer sb = null;
			String params = "";

			/***
			 * 描述 TODO
			 * 以下是用于上传参数
			 */
			if (param != null && param.size() > 0) {
				Iterator<String> it = param.keySet().iterator();
				while (it.hasNext()) {
					sb = null;
					sb = new StringBuffer();
					String key = it.next();
					String value = param.get(key);
					sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
					sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END);
					sb.append(value).append(LINE_END);
					params = sb.toString();
					Log.i(TAG, key+"="+params+"##");
					dos.write(params.getBytes());
//					dos.flush();
				}
			}

			sb = null;
			params = null;
			sb = new StringBuffer();
			/**
			 * 描述 TODO
			 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
			 * filename是文件的名字，包含后缀名的 比如:abc.png
			 */
			sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
			sb.append("Content-Disposition:form-data; name=\"" + fileKey + "\"; filename=\"" + "head.jpg" + "\"" + LINE_END);
			sb.append("Content-Type:image/pjpeg" + LINE_END); // 这里配置的Content-type很重要的 ，用于服务器端辨别文件的类型的
			sb.append(LINE_END);
			params = sb.toString();
			sb = null;


			Log.i(TAG, "head.jpg"+"=" + params+"##");
			dos.write(params.getBytes());

			/**
			 * 描述 TODO
			 * 上传文件
			 **/
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			file.compress(Bitmap.CompressFormat.PNG, 100, baos);
			InputStream is = new ByteArrayInputStream(baos .toByteArray());
			onUploadProcessListener.initUpload();//表示开始上传
			byte[] bytes = new byte[4096];
			int len = 0;
			int curLen = 0;
			while ((len = is.read(bytes)) != -1) {
				System.out.println("上传...read"+len);
				curLen += len;
					dos.write(bytes, 0, len);
				onUploadProcessListener.onUploadProcess(curLen);
			}
			is.close();
			dos.write(LINE_END.getBytes());
			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
			dos.write(end_data);
			dos.flush();
//			dos.write(tempOutputStream.toByteArray());
			/**
			 * 描述 TODO
			 * 获取响应码 200=成功 当响应成功，获取响应的流
			 */
			Log.e(TAG, "response conn:" + conn.toString()+"  code=="+conn.getRequestMethod()+"   msg=="+conn.getResponseMessage());

			int res = conn.getResponseCode();
			responseTime = System.currentTimeMillis();
			this.requestTime = (int) ((responseTime-requestTime)/1000);
			Log.e(TAG, "response code:" + res);
			if (res == 200) {
				Log.e(TAG, "request success");
				InputStream input = conn.getInputStream();
				StringBuffer sb1 = new StringBuffer();
				int ss;
				while ((ss = input.read()) != -1) {
					sb1.append((char) ss);
				}
				result = sb1.toString();
				Log.e(TAG, "result : " + result);
				sendMessage(UPLOAD_SUCCESS_CODE,result);
				return;
			} else {
				Log.e(TAG, "request error");
				sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败：code=" + res);
				return;
			}
		} catch (MalformedURLException e) {
			sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败：error=" + e.getMessage());
			e.printStackTrace();
			return;
		} catch (IOException e) {
			sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败：error=" + e.getMessage());
			e.printStackTrace();
			return;
		}
	}

	private void toUploadErrorFile(File file, String fileKey, String RequestURL, Map<String, String> param) {

		String result = null;
		requestTime= 0;

		long requestTime = System.currentTimeMillis();
		long responseTime = 0;
		HttpURLConnection conn=null;
		InputStream is=null;
		try {
			URL url = new URL(RequestURL);
			conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(readTimeOut);
			conn.setConnectTimeout(connectTimeout);
			conn.setDoInput(true); // 允许输入流
			conn.setDoOutput(true); // 允许输出流
			conn.setUseCaches(false); // 不允许使用缓存
			conn.setRequestMethod("POST"); // 请求方式
			conn.setRequestProperty("Charset", CHARSET); // 设置编码
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
		    conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
			//conn.setRequestProperty("Content-Type", CONTENT_TYPE);
//			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			/**
			 * 描述 TODO
			 * 当文件不为空，把文件包装并且上传
			 */
			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
			StringBuffer sb = null;
			String params = "";

			/***
			 * 描述 TODO
			 * 以下是用于上传参数
			 */
			if (param != null && param.size() > 0) {
				Iterator<String> it = param.keySet().iterator();
				while (it.hasNext()) {
					sb = null;
					sb = new StringBuffer();
					String key = it.next();
					String value = param.get(key);
					sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
					sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END);
					sb.append(value).append(LINE_END);
					params = sb.toString();
					Log.i(TAG, key+"="+params+"##");
					dos.write(params.getBytes());
//					dos.flush();
				}
			}else{
				Log.i(TAG, key+"="+params+"##   null");
			}


			sb = null;
			params = null;
			sb = new StringBuffer();
			/**
			 * 描述 TODO
			 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
			 * filename是文件的名字，包含后缀名的 比如:abc.png
			 */
			sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
		    //sb.append("Content-Disposition:form-data; name=\"" + fileKey +  "\"" + LINE_END);
			sb.append("Content-Disposition:form-data; name=\"" + "file" + "\"; filename=\"" + file.getName() + "\"" + LINE_END);
			//sb.append("Content-Type:image/pjpeg" + LINE_END);
			sb.append("Content-Type:multipart/form-data" + LINE_END); // 这里配置的Content-type很重要的 ，用于服务器端辨别文件的类型的
			sb.append(LINE_END);

			params = sb.toString();
			sb = null;

			Log.i(TAG, "toUploadErrorFile"+"=" + params+"##");
			dos.write(params.getBytes());
           // dos.write(readFile(file));
			/**
			 * 描述 TODO
			 * 上传文件
			 **/
			/*ByteArrayOutputStream baos = new ByteArrayOutputStream();
			file.compress(Bitmap.CompressFormat.PNG, 100, baos);*/
			is = new FileInputStream(file);
			//is = new ByteArrayInputStream(baos .toByteArray());
			onUploadProcessListener.initUpload();//表示开始上传
			byte[] bytes = new byte[1024];
			int len = 0;
			int curLen = 0;
			while ((len = is.read(bytes)) != -1) {
				curLen += len;
				System.out.println(len+"  上传..."+curLen);
				try {
					dos.write(bytes, 0, len);
				}catch (Exception e){
					Log.i(TAG,"READ  CRASH=="+e.toString());
				}
				//onUploadProcessListener.onUploadProcess(curLen);
			}
			is.close();
			dos.write(LINE_END.getBytes());
			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
			dos.write(end_data);
			dos.flush();
//			dos.write(tempOutputStream.toByteArray());
			/**
			 * 描述 TODO
			 * 获取响应码 200=成功 当响应成功，获取响应的流
			 */
		//	Log.e(TAG, "RequestURL :" + RequestURL+"   filekey=="+fileKey+"   file =="+file.getAbsolutePath()+"   "+file.getName());

			Log.e(TAG, "response conn:" + conn.toString()+"  code=="+conn.getRequestMethod()+"   msg=="+conn.getResponseMessage());
			int res = conn.getResponseCode();
			responseTime = System.currentTimeMillis();
			this.requestTime = (int) ((responseTime-requestTime)/1000);
			Log.e(TAG, "response code:" + res);
			if (res == 200) {
				Log.i(TAG, "request success");
				InputStream input = conn.getInputStream();
				StringBuffer sb1 = new StringBuffer();
				int ss;
				while ((ss = input.read()) != -1) {
					sb1.append((char) ss);
				}
				result = sb1.toString();
				Log.e(TAG, "result : " + result);
				input.close();//关闭流
				sendMessage(UPLOAD_SUCCESS_CODE, result);
				return;
			} else {
				Log.e(TAG, "request error");
				sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败：code=" );
				return;
			}

		} catch (MalformedURLException e) {

			sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败：error=" + e.getMessage());
			e.printStackTrace();
			return;
		} catch (IOException e) {
			sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败：error=" + e.getMessage());
			e.printStackTrace();
			return;
		}catch (Exception e){
			Log.e(TAG, "Exception error"+e.toString());
		} finally {
			Log.e(TAG, "关闭流的操作");
			if (is!=null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
	}


	/**
	 * 上传文件到服务器
	 * @param
	 * @param uploadUrl     上传服务器地址
	 * @param oldFilePath       本地文件路径
	 */
	public  void uploadLogFile(String uploadUrl, String oldFilePath){
		try {
			URL url = new URL(uploadUrl);
			HttpURLConnection con = (HttpURLConnection)url.openConnection();

			// 允许Input、Output，不使用Cache
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);

			con.setConnectTimeout(50000);
			con.setReadTimeout(50000);
			// 设置传送的method=POST
			con.setRequestMethod("POST");
			//在一次TCP连接中可以持续发送多份数据而不会断开连接
			con.setRequestProperty("Connection", "Keep-Alive");
			//设置编码
			con.setRequestProperty("Charset", "UTF-8");
			//text/plain能上传纯文本文件的编码格式   text/plain  multipart/form-data
			//con.setRequestProperty("Content-Type", "multipart/form-data");
			con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			con.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

			// 设置DataOutputStream
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());

			// 取得文件的FileInputStream
			FileInputStream fStream = new FileInputStream(oldFilePath);
			// 设置每次写入1024bytes
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];

			int length = -1;
			// 从文件读取数据至缓冲区
			while ((length = fStream.read(buffer)) != -1) {
				System.out.println(length+"  上传...");
				// 将资料写入DataOutputStream中
				ds.write(buffer, 0, length);

			}
			ds.flush();
			fStream.close();
			ds.close();
			Log.e(TAG, "response conn:" + con.toString()+"  code=="+con.getRequestMethod()+"   msg=="+con.getResponseMessage());
			Log.e(TAG,"getResponseCode=="+con.getResponseCode());
			if(con.getResponseCode() == 200){
				InputStream input = con.getInputStream();
				StringBuffer sb1 = new StringBuffer();
				int ss;
				while ((ss = input.read()) != -1) {
					sb1.append((char) ss);
				}
				String result = sb1.toString();
				Log.e(TAG, "result : " + result);
				sendMessage(UPLOAD_SUCCESS_CODE,result);
			}
		} catch (MalformedURLException e) {
			Log.e(TAG, "MalformedURLException : " + e.toString());
			sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败：error=" + e.getMessage());
			e.printStackTrace();
			return;
		} catch (IOException e) {
			Log.e(TAG, "IOException : " + e.toString());
			sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败：error=" + e.getMessage());
			e.printStackTrace();
			return;
		}
	}

	/**
	 * 描述 TODO
	 * 发送上传结果
	 * @param responseCode
	 * @param responseMessage
	 */
	private void sendMessage(int responseCode, String responseMessage)
	{
		onUploadProcessListener.onUploadDone(responseCode, responseMessage);
	}

	/**
	 * 描述 TODO
	 * 下面是一个自定义的回调函数，用到回调上传文件是否完成
	 * @author shimingzheng
	 */
	public static interface OnUploadProcessListener {
		/**
		 * 描述 TODO
		 * 上传响应
		 * @param responseCode
		 * @param message
		 */
		void onUploadDone(int responseCode, String message);
		/**
		 * 描述 TODO
		 * 上传中
		 * @param uploadSize
		 */
		void onUploadProcess(int uploadSize);
		/**
		 * 描述 TODO
		 * 准备上传
		 * @paramfileSize
		 */
		void initUpload();
	}
	private OnUploadProcessListener onUploadProcessListener;



	public void setOnUploadProcessListener(OnUploadProcessListener onUploadProcessListener) {
		this.onUploadProcessListener = onUploadProcessListener;
	}
	/**
	 * 描述 TODO
	 * 获取上传使用的时间
	 * @return
	 */
	public static int getRequestTime() {
		return requestTime;
	}

	private byte[] readFile(File file) {
		// 需要读取的文件，参数是文件的路径名加文件名
		if (file.isFile()) {
			// 以字节流方法读取文件

			FileInputStream fis = null;
			try {
				fis = new FileInputStream(file);
				// 设置一个，每次 装载信息的容器
				byte[] buffer = new byte[1024];
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				// 开始读取数据
				int len = 0;// 每次读取到的数据的长度
				while ((len = fis.read(buffer)) != -1) {// len值为-1时，表示没有数据了
					// append方法往sb对象里面添加数据
					outputStream.write(buffer, 0, len);
				}
				// 输出字符串
				return outputStream.toByteArray();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("文件不存在！");
		}
		return null;
	}





}
